package com.example.zsr.downloadcontinue.download;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zsr.downloadcontinue.DownlistAdapter;
import com.example.zsr.downloadcontinue.MyApplication;
import com.example.zsr.downloadcontinue.R;
import com.example.zsr.downloadcontinue.ToolUtils.ContantsUtils;
import com.example.zsr.downloadcontinue.entity.DownloadConfigGuration;
import com.example.zsr.downloadcontinue.entity.FileInfo;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhengshaorui on 2017/3/1.
 */

public class DownloadTaskManger {
    private static final String TAG = "DownloadTaskManger";
    private static Context mContext = MyApplication.getAppContext();
    private Activity activity;
    public static int TaskCount;
    private List<FileInfo> mFileInfoList;
    private ListView mListView;
    private DownlistAdapter mDownlistAdapter;


    //正在下载的任务
    private List<FileInfo> mFileInfoLoadings = new ArrayList<FileInfo>();
    //等待的任务
    private List<FileInfo> mFileInfoWaitings = new ArrayList<FileInfo>();

    private ProgressBar mProgressBar;
    public static class Holder{
        private static DownloadTaskManger sDownloadTaskManger = new DownloadTaskManger();
        public static DownloadTaskManger getInstance(){
            return  sDownloadTaskManger;
        }
    }

    public void init(Activity context,int taskcount){
        activity = context;
        this.TaskCount = taskcount;
        mFileInfoList = new ArrayList<FileInfo>();
        mListView = (ListView) activity.findViewById(R.id.file_list);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ContantsUtils.UPDATE_PROGRESS);
        filter.addAction(ContantsUtils.FILE_FINISHED);
        activity.registerReceiver(broadcastReceiver,filter);

        mProgressBar = (ProgressBar) activity.findViewById(R.id.file_bar);
    }

   // private Map<String,FileInfo> mTaskFileinfo = new LinkedHashMap<String,FileInfo>();


    public void addTaskConfig(DownloadConfigGuration configGuration){
        FileInfo fileInfo = new FileInfo(configGuration.getFileurl(), configGuration.getFilename(),
                getFileDir(),null, 0,0, configGuration.getThreadcount(), 0,0,
                0, ContantsUtils.FILE_NOT_DOWNLOAD,ContantsUtils.START,0);
       // mTaskFileinfo.put(fileInfo.getApkurl(),fileInfo);

        mFileInfoList.add(fileInfo);
    }

    public void completedAndStartDownload(){

        for (int i = 0; i < mFileInfoLoadings.size(); i++) {
            mFileInfoLoadings.remove(i);
        }

        for (int i = 0; i < mFileInfoWaitings.size(); i++) {
            mFileInfoWaitings.remove(i);
        }

        mDownlistAdapter = new DownlistAdapter(mFileInfoList,activity);
        mListView.setAdapter(mDownlistAdapter);
        /*for (FileInfo fileInfo : mFileInfoList) {
            Intent intent = new Intent(mContext,DownloadService.class);
            intent.putExtra("fileinfo",fileInfo);
            mContext.startService(intent);
        }*/
        for (int i = 0; i < mFileInfoList.size(); i++) {
            FileInfo fileInfo = mFileInfoList.get(i);

            if (i < TaskCount){
                mFileInfoLoadings.add(fileInfo);
            }else{
                mFileInfoWaitings.add(fileInfo);
            }
        }

        startLoading();
    }


    private void startLoading(){
        for (FileInfo fileInfo : mFileInfoLoadings){

            Intent intent = new Intent(mContext,DownloadService.class);
            intent.putExtra("fileinfo",fileInfo);
            mContext.startService(intent);
        }
    }



    /**
     * 获取文件的路径
     * @return
     */
    private String getFileDir(){
        String dir = null;
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){
            dir = mContext.getExternalCacheDir()+"/mydownload/";
        }else {
            dir = mContext.getCacheDir()+"/mydownload/";
        }
        return dir;
    }

    /**
     * 下载回调函数
     */
    public  DownloadCallback mDownloadCallback = new DownloadCallback() {
        @Override
        public void success(FileInfo fileInfo) {

            for (int i = 0; i < mFileInfoLoadings.size(); i++) {
                FileInfo info = mFileInfoLoadings.get(i);
                info.setBtnstatus(ContantsUtils.HASBEENSTART);
                mFileInfoLoadings.set(i,info); //刷新task的状态

                if (fileInfo.getApkurl().equals(mFileInfoLoadings.get(i).getApkurl())){
                    mFileInfoLoadings.remove(i);
                }
            }
            if (mFileInfoLoadings.size() >= 0  && mFileInfoLoadings.size() < TaskCount) {
                if (mFileInfoWaitings.size() > 0) {
                    mFileInfoLoadings.add(mFileInfoWaitings.get(0));
                    mFileInfoWaitings.remove(0);
                }
            }
            startLoading();


        }

        @Override
        public void failed(int errorcode,final String errorMsg, final FileInfo fileInfo) {
            // you can do something
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, fileInfo.getFileName()+"下载失败: "+errorMsg,
                            Toast.LENGTH_SHORT).show();
                }
            });

        }

        @Override
        public void downloadStatus(String fileUrl, int status) {
            Log.d(TAG, "downloadStatus: " + status);
        }
    };


    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(ContantsUtils.UPDATE_PROGRESS)) {

                try {
                    FileInfo fileInfo = (FileInfo) intent.getSerializableExtra(ContantsUtils.FILEINFO);
                    int progress = fileInfo.getProgress();

                    ProgressBar seekbar = (ProgressBar) mListView.findViewWithTag(fileInfo.getApkurl()+ContantsUtils.TAG_PROGRESSBAR);
                    TextView textProgress = (TextView)mListView.findViewWithTag(fileInfo.getApkurl()+ContantsUtils.TAG_TEXTPROGRESS);
                    TextView textfilesize = (TextView)mListView.findViewWithTag(fileInfo.getApkurl()+ContantsUtils.TAG_FILESIZE);
                    TextView textstatus = (TextView) mListView.findViewWithTag(fileInfo.getApkurl() + ContantsUtils.TAG_FILESTATUS);

                    float speed = fileInfo.getSpeed();
                    if (speed > 1024){
                        String speedString = getFloatToString(speed/1024);
                        textstatus.setText(speedString+"M/s");
                    }else{
                        String speedString  = getFloatToString(speed);
                        textstatus.setText(speedString+"kb/s");
                    }

                    seekbar.setProgress(progress);
                    textProgress.setVisibility(View.VISIBLE);
                    textProgress.setText(progress+"%");


                    textfilesize.setVisibility(View.VISIBLE);
                    float filedownload = fileInfo.getFiledown();
                    float filesize = fileInfo.getFilesize();

                    String mCurProgress = getFloatToString(filedownload);
                    String mProgressLength = getFloatToString(filesize);
                    textfilesize.setText(mCurProgress + "MB" + " / " + mProgressLength + "MB");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            if (action.equals(ContantsUtils.FILE_FINISHED)){


                try {
                    FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileinfo");
                    ProgressBar progressBar = (ProgressBar) mListView.findViewWithTag(fileInfo.getApkurl() + ContantsUtils.TAG_PROGRESSBAR);
                    TextView textProgress = (TextView) mListView.findViewWithTag(fileInfo.getApkurl() + ContantsUtils.TAG_TEXTPROGRESS);
                    TextView textfilesize = (TextView) mListView.findViewWithTag(fileInfo.getApkurl() + ContantsUtils.TAG_FILESIZE);
                    TextView textstatus = (TextView) mListView.findViewWithTag(fileInfo.getApkurl() + ContantsUtils.TAG_FILESTATUS);
                    ImageView imageview = (ImageView) mListView.findViewWithTag(fileInfo.getApkurl() + ContantsUtils.TAG_FILEBTN);


                    progressBar.setProgress(100);

                    textProgress.setVisibility(View.INVISIBLE);

                    textfilesize.setVisibility(View.INVISIBLE);
                    textstatus.setText("已完成");
                    imageview.setImageResource(R.mipmap.start);


                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

        }
    };

    private String getFloatToString(Float value){
        DecimalFormat decimalFormat =
                new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        return  decimalFormat.format(value);
    }

}
